package com.example.user.manger;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.core.constants.CacheConstants;
import com.example.common.redis.service.RedisService;
import com.example.common.security.service.TokenService;
import com.example.user.domain.student.Student;
import com.example.user.domain.student.vo.StudentDetailVO;
import com.example.user.mapper.StudentMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
public class StudentCacheManager {
    @Autowired
    private RedisService redisService;


    @Autowired
    private TokenService tokenService;


    @Autowired
    private StudentMapper studentMapper;

    /* 用户个人中心功能,查看个人详情 */
    public StudentDetailVO getStudentById(Long studentId) {
        String studentKey = getStudentKey(studentId);
        StudentDetailVO studentDetailVO = redisService.getCacheObject(studentKey, StudentDetailVO.class);
        if (studentDetailVO != null) {
            //将缓存延长10min
            redisService.expire(studentKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
            return studentDetailVO;
        }
        Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>()
                .select(Student::getStudentId,
                        Student::getNickName,
                        Student::getEmail,
                        Student::getPhone,
                        Student::getHeadImage,
                        Student::getAge,
                        Student::getSex,
                        Student::getWechat,
                        Student::getSchoolName,
                        Student::getMajorName,
                        Student::getIntroduce,
                        Student::getStatus)
                .eq(Student::getStudentId, studentId));
        if (student == null) {
            return null;
        }
        refreshStudent(student);
        studentDetailVO = new StudentDetailVO();
        BeanUtil.copyProperties(student, studentDetailVO);
        return studentDetailVO;
    }

    public void refreshStudent(Student student) {
        //刷新用户缓存
        String studentKey = getStudentKey(student.getStudentId());
        redisService.setCacheObject(studentKey, student);
        //设置用户缓存有效期为10分钟
        redisService.expire(studentKey, CacheConstants.USER_EXP, TimeUnit.MINUTES);
    }


    //u:d:用户id
    private String getStudentKey(Long studentId) {
        return CacheConstants.STUDENT_DETAIL + studentId;
    }
}
